package com.yuju.log.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuju.cache.RedisCache;
import com.yuju.common.Result;
import com.yuju.constant.CacheKey;
import com.yuju.enums.LogBizTypeEnum;
import com.yuju.group.model.EmployeeModel;
import com.yuju.group.service.IEmployeeService;
import com.yuju.hotel.enums.CustomersEnum;
import com.yuju.hotel.model.PriceDetailModel;
import com.yuju.hotel.model.PriceSchemeModel;
import com.yuju.hotel.model.RoomTypeModel;
import com.yuju.hotel.service.IPriceDetailService;
import com.yuju.hotel.service.IPriceSchemeService;
import com.yuju.hotel.service.IRoomTypeService;
import com.yuju.log.model.LogBizRecordModel;
import com.yuju.log.model.LogBizTypeModel;
import com.yuju.log.service.ILogBizRecordService;
import com.yuju.log.service.IPriceSchemeLogService;
import com.yuju.persist.util.IdWorkerInstance;
import com.yuju.util.Format;
import com.yuju.vo.hotel.PriceSchemeVO;

/**
 * 
 * 类名：PriceSchemeLogServiceImpl  <br />
 *
 * 功能：价格方案日志服务
 *
 * @author : xuehj <br />
 * @Date : 2018年1月30日 下午1:46:19  <br />
 * @version : 1.1 <br />
 */
@Service
public class PriceSchemeLogServiceImpl implements IPriceSchemeLogService {
	private static final Logger logger = LoggerFactory.getLogger(PriceSchemeLogServiceImpl.class);
	private RedisCache cache = RedisCache.getInstance();
	private static ThreadLocal<String> requestThread = new ThreadLocal<String>();

	@Autowired
	private IRoomTypeService roomTypeService;
	@Autowired
	private ILogBizRecordService logBizRecordService ;
	@Autowired
	private IEmployeeService employeeService;
	@Autowired
	private IPriceSchemeService priceSchemeService;
	@Autowired
	private IPriceDetailService priceDetailService;
	
	
	
	
	@Override
	public void before(String path, JSONObject obj) {
		try {
			System.err.println("===================before价格方案日志服务开始===================");
			System.out.println(path);
			switch (path) {
			case "/priceScheme/update":
			{
				priceScheme_get(obj);
				break;
			}
			default:
				System.out.println("no switch");
		}
			
			
			System.err.println("===================before价格方案日志服务结束===================");
		} catch(Exception e) {
			logger.debug("价格方案日志异常：", e);
		}
	}

	@Override
	public void log(String path, JSONObject obj, Result ret) {
		try {
			System.err.println("===================价格方案日志服务开始===================");
			System.out.println(path);
			
			
			switch (path) {
				case "/priceScheme/save":
				{
					priceScheme_save(obj);
					break;
				}
				case "/priceScheme/update":
				{
					priceScheme_update(obj);
					break;
				}
				default:
					System.out.println("no switch");
			}
			
			System.err.println("===================价格方案日志服务结束===================");
		} catch(Exception e) {
			logger.debug("价格方案日志异常：", e);
		}
	}

	/**
	 * 
	 * 功能：新增价格方案日志<br/>
	 *
	 * @author zhousc
	 * @Date 2018年1月31日 下午3:13:44 <br/>
	 */
	private void priceScheme_save(JSONObject obj){
		LogBizTypeModel modelForT = getLogBizType(LogBizTypeEnum.ADD_PRICE_SCHEME_LOG_TYPE.getCode());
		// 日志模板
		String template = modelForT.getTemplate();
		/*模板替代获取*/
		PriceSchemeVO vo = obj.toJavaObject(PriceSchemeVO.class);
		//方案名称
		template = template.replace("#priceSchemeName#", vo.getName());
		//方案类别
		template = template.replace("#schemeType#", CustomersEnum.getTypeName(vo.getSchemeType()));
		//含早
		template = template.replace("#breakCount#", vo.getBreakCount().toString());
		//有效时间起止
		template = template.replace("#effectiveDate#", Format.getForMatDayForFull(vo.getEffectiveDate()));
		template = template.replace("#expiry_date#", Format.getForMatDayForFull(vo.getExpiryDate()));
		//取价格明细
		JSONArray jsonArray = obj.getJSONArray("priceDetailModels");
		//将array数组转换成字符串  
		String js = jsonArray.toJSONString();
		//把字符串转换成集合  
		List<PriceDetailModel> priceDetailModels = (List<PriceDetailModel>) JSONObject.parseObject(js,  new TypeReference<ArrayList<PriceDetailModel>>() {});
		String roomTypes = "";
		for(int i = 0; i < priceDetailModels.size(); i++){
			//根据roomId查询对应房型名称
			RoomTypeModel findById = roomTypeService.findById(priceDetailModels.get(i).getRoomTypeId());
			//拼接价格明细
			roomTypes += findById.getName() + ":" + priceDetailModels.get(i).getPrice() + ";" ;
		}
		
		//价格明细
		template = template.replace("#roomTypes#", roomTypes);
		//保存日志
		LogBizRecordModel logBizRecordModel = new LogBizRecordModel();
		logBizRecordModel.setGroupId(obj.getString("groupId"));
		logBizRecordModel.setHotelId(obj.getString("hotelId"));
		//父ID
		LogBizTypeModel logBizType = getLogBizType(modelForT.getParentCode());
		logBizRecordModel.setLogBizTypeId(logBizType.getId());
		//父name
		logBizRecordModel.setLogBizTypeName(modelForT.getParentCodeName());
		//类型ID
		logBizRecordModel.setBizTypeId(new Byte(modelForT.getId()));
		//类型code
		logBizRecordModel.setBizTypeCode(modelForT.getCode());
		//类型name
		logBizRecordModel.setBizTypeName(modelForT.getName());
		//日志描述
		logBizRecordModel.setBizDetail(template);
		//创建人信息
		logBizRecordModel.setCreateUserId(obj.getString("empId"));
		EmployeeModel empModel = employeeService.findById(obj.getString("empId"));
		logBizRecordModel.setCreateUserName(empModel.getName());
		logBizRecordModel.setRemark(vo.getName());
		//保存日志
		logBizRecordService.save(logBizRecordModel);
	}
	
	/**
	 * 
	 * 功能：修改价格方案前先将原来的信息保存到redis里<br/>
	 *
	 * @author zhousc
	 * @Date 2018年1月31日 下午3:14:49 <br/>
	 */
	private void priceScheme_get(JSONObject obj){
		//获取价格方案ID
		String id = obj.getString("id");
		//根据ID获取价格方案信息
		PriceSchemeModel priceSchemeModel = priceSchemeService.findById(id);
		//根据价格方案ID查询对应的价格明细
		PriceDetailModel priceDetailModel = new PriceDetailModel();
		priceDetailModel.setPirceSchemeId(id);
		List<PriceDetailModel> priceDetailModels = priceDetailService.list(priceDetailModel);
		priceSchemeModel.setPriceDetailModels(priceDetailModels);
		//缓存到redis
		String requestId = IdWorkerInstance.getIdStr();
		requestThread.set(requestId);
		// 查询房间改变之前的状态放到redis中
		RedisCache.getInstance().addCache(requestThread.get(),priceSchemeModel);
	}
	
	/**
	 * 
	 * 功能：修改价格方案日志<br/>
	 *
	 * @author zhousc
	 * @Date 2018年1月31日 下午3:34:22 <br/>
	 */
	private void priceScheme_update(JSONObject obj){
		LogBizTypeModel modelForT = getLogBizType(LogBizTypeEnum.MODIFY_PRICE_SCHEME_LOG_TYPE.getCode());
		// 日志模板
		String template = modelForT.getTemplate();
		/*模板替代获取*/
		PriceSchemeVO vo = obj.toJavaObject(PriceSchemeVO.class);
		JSONArray jsonArray = obj.getJSONArray("priceDetailModels");
		//将array数组转换成字符串  
		String js = jsonArray.toJSONString();
		//把字符串转换成集合  
		List<PriceDetailModel> priceDetailModels = (List<PriceDetailModel>) JSONObject.parseObject(js,  new TypeReference<ArrayList<PriceDetailModel>>() {});
		//取出缓存中的原始数据
		PriceSchemeModel priceSchemeModel = (PriceSchemeModel) RedisCache.getInstance().get(requestThread.get());
		
		//日志模板替换
		template = template.replace("#oldPriceScheme#", priceSchemeModel.getName());
		template = template.replace("#newPriceSchemeName#", vo.getName());
		template = template.replace("#oldSchemeType#", CustomersEnum.getTypeName(priceSchemeModel.getSchemeType()));
		template = template.replace("#newSchemeType#", CustomersEnum.getTypeName(vo.getSchemeType()));
		template = template.replace("#oldBreakCount#", priceSchemeModel.getBreakCount().toString());
		template = template.replace("#newBreakCount#", vo.getBreakCount().toString());
		template = template.replace("#oldEffectiveDate#", Format.getForMatDayForFull(priceSchemeModel.getEffectiveDate()));
		template = template.replace("#oldExpiry_date#", Format.getForMatDayForFull(priceSchemeModel.getExpiryDate()));
		template = template.replace("#newEffectiveDate#", Format.getForMatDayForFull(vo.getEffectiveDate()));
		template = template.replace("#newExpiry_date#", Format.getForMatDayForFull(vo.getExpiryDate()));
		String roomTypes = "";
		//拼接价格明细
		List<PriceDetailModel> models = priceSchemeModel.getPriceDetailModels();
		for(int i = 0; i < models.size(); i++){
			//查询房型名称
			RoomTypeModel roomTypeModel = roomTypeService.findById(models.get(i).getRoomTypeId());
			//查询新价格
			PriceDetailModel priceDetailModel = new PriceDetailModel();
			priceDetailModel.setRoomTypeId(models.get(i).getRoomTypeId());
			priceDetailModel.setPirceSchemeId(models.get(i).getPirceSchemeId());
			PriceDetailModel find = priceDetailService.find(priceDetailModel);
			//拼接描述
			roomTypes += roomTypeModel.getName() + ":" + models.get(i).getPrice() + "-" + find.getPrice() + ";"; 
		}
		template = template.replace("#roomTypes#", roomTypes);
		
		//保存日志
		LogBizRecordModel logBizRecordModel = new LogBizRecordModel();
		logBizRecordModel.setGroupId(obj.getString("groupId"));
		logBizRecordModel.setHotelId(obj.getString("hotelId"));
		//父ID
		LogBizTypeModel logBizType = getLogBizType(modelForT.getParentCode());
		logBizRecordModel.setLogBizTypeId(logBizType.getId());
		//父name
		logBizRecordModel.setLogBizTypeName(modelForT.getParentCodeName());
		//类型ID
		logBizRecordModel.setBizTypeId(new Byte(modelForT.getId()));
		//类型code
		logBizRecordModel.setBizTypeCode(modelForT.getCode());
		//类型name
		logBizRecordModel.setBizTypeName(modelForT.getName());
		//日志描述
		logBizRecordModel.setBizDetail(template);
		//创建人信息
		logBizRecordModel.setCreateUserId(obj.getString("empId"));
		//价格方案名称
		logBizRecordModel.setRemark(vo.getName());
		EmployeeModel empModel = employeeService.findById(obj.getString("empId"));
		logBizRecordModel.setCreateUserName(empModel.getName());
		//保存日志
		logBizRecordService.save(logBizRecordModel);
		
	}
	/**
	 * 
	 * 功能：根据日志类型code查询日志类别信息<br/>
	 *
	 * @author zhousc
	 * @Date 2018年1月31日 下午3:02:25 <br/>
	 */
	private LogBizTypeModel getLogBizType(String code){
		// 从缓存中去除价格方案日志配置信息
		String logBizForT = (String) cache.get
				(code + CacheKey.KEY_CACHE_LOG_BIZ_TYPE);
		
		JSONObject jsonForT = JSONObject.parseObject(logBizForT);
		LogBizTypeModel modelForT = JSONObject.toJavaObject(jsonForT, LogBizTypeModel.class);
		return modelForT;
	}
	
}
